using System.Collections.Generic;
using UnityEngine;
using Yoozoo.Libs;
using Yoozoo.Managers;

namespace Gameplay.PVE.TurnBase
{
    public class MoveComponent : IComponent,ITransmit
    {
        private float autoReturnTime = 0.5f;
        private float startStillTime;//开始停止的时间，如果位置不在出生地，并且停止超过一定时间，就会自动返回出生地
        
        //寻路相关
        private List<Vector3> pathList = new List<Vector3>();
        private Vector3 lastTargetPosition;
        private int nextIndex = 0;
        public bool needRepath = false;
        private int currentFrame;

        private RandomMoveAction moveAction;

        void IClass.OnReset()
        {

        }
        private BattleUnit unit;
        void IComponent.OnInitialize(BattleUnit unit)
        {
            startStillTime = 1;
            autoReturnTime = 0;
            this.unit = unit;
        }

        void IComponent.OnUpdate()
        {
            /*if (unit.Data.id == 0 && (needRepath || currentFrame % 10 == unit.Data.id))
            {
                RePath(unit.Data.position, unit.Data.targetPosition);
                needRepath = false;
            }

            currentFrame++;
            lastTargetPosition = unit.Data.targetPosition;
            UpdateRoadPath();*/
            moveAction?.Update();
            //unit.gameObject.transform.forward = unit.Data.forward;
        }

        public void LateUpdate()
        {
            if (unit.Data.velocity.sqrMagnitude > 0 || unit.Data.IsInAction || unit.Data.isDead || unit.Data.isJoining)
            {
                startStillTime = 0;
            }
            else if (startStillTime == 0 && Vector3.Distance(unit.Data.position,unit.Data.birthPosition) > 0.2f)
            {
                autoReturnTime = Random.Range(0, 0.5f);
                startStillTime = TimeManager.logicTime;
            }
            
            if (unit.Data.velocity.sqrMagnitude > 0 || unit.Data.IsInAction || unit.Data.isDead || (moveAction != null && moveAction.IsWorking))
            {
                startStillTime = 0;
            }
            var v = unit.Data.velocity * TimeManager.GameDeltaTime;
            var position = unit.Data.position + v;
            if (position.y < 0)
            {
                position.y = 0;
            }
            
                        
            //判断是否需要自动走回
            if (startStillTime != 0 && TimeManager.logicTime - startStillTime > autoReturnTime)
            {
                var speed = DoAutoReturn();
                position += speed;
                if (speed == Vector3.zero)
                {
                    startStillTime = 0;
                    unit.Data.isJoining = false;
                }
                unit.Data.SetForward(speed);
            }
            unit.Data.SetPosition(position);
            
            unit.gameObject.transform.forward = unit.Data.forward;
            unit.gameObject.transform.position = unit.Data.position;
        }
        
        
        private bool MoveToTargetPosition(Vector3 targetPosition)
        {
            Vector3 diff = targetPosition - unit.Data.position;
            if (diff != Vector3.zero)
            {
                unit.Data.SetForward(diff);
            }
            
            float distance = diff.magnitude;
            float normalizedSpeedValue = unit.Data.moveSpeed * TimeManager.GameDeltaTime;
            if (normalizedSpeedValue < distance)
            {
                Vector3 normalizedSpeed = normalizedSpeedValue * diff.normalized;
                unit.Data.SetPosition(unit.Data.position + normalizedSpeed);
                return false;
            }
            else
            {
                unit.Data.SetPosition(targetPosition);
                return true;
            }
        }
        
        private void ToNextPoint()
        {
            unit.Data.SetPosition(pathList[nextIndex]);
            if (nextIndex < pathList.Count - 1)
            {
                nextIndex++;
            }
            else
            {
                pathList.Clear();
                lastTargetPosition = Vector3.zero;
                //UpdateData();
            }
        }
        
        private void UpdateRoadPath()
        {
            if (pathList.Count > nextIndex )
            {
                if (nextIndex > 0)
                {
                    Vector3 targetPosition = pathList[nextIndex];
                    Vector3 lastPosition = pathList[nextIndex - 1];
                    bool isReach = MoveToTargetPosition(targetPosition);
                    if (isReach)
                    {
                        ToNextPoint();
                    }
                }
                else
                {
                    ToNextPoint();
                }
            }
        }

        
        private void RePath(Vector3 start,Vector3 end)
        {
            //pathList = PveFindPathManager.Instance.GetPathByObstacle(unit.Data.id,start, end);
            nextIndex = 0;
            ToNextPoint();
        }

        

        void IComponent.OnBirth()
        {
            /*if (unit.Data.config.type == 0)
            {
                moveAction = ClassManager.Get<RandomMoveAction>();
                moveAction.Init(unit);
            }*/
        }
        
        void IComponent.OnDead()
        {
            
        }
        
        void ITransmit.OnTransmit(ETransmitType type, BaseTransmitArg arg)
        {
            if (type == ETransmitType.GoToNextStage)
            {
                unit.Data.isInBirthPosition = false;
                unit.Data.birthPosition = TurnBaseManager.Instance.GetBirthPosition(unit.Data.index, unit.Data.team);
            }
            else if (type == ETransmitType.RoundStart)
            {
                //unit.Data.SetPosition(unit.Data.birthPosition);
                unit.Data.SetForward(unit.Data.birthForward);
            }
            else if (type == ETransmitType.StageStart)
            {
                unit.Data.SetPosition(unit.Data.birthPosition);
                unit.Data.SetForward(unit.Data.birthForward);
            }
            /*else if (type == ETransmitType.MoveToBirthPosition)
            {
                
            }*/
        }

        private Vector3 DoAutoReturn()
        {
            Vector3 diff = unit.Data.birthPosition - unit.Data.position;
            float speedValue = unit.Data.moveSpeed * TimeManager.GameDeltaTime;
            float diffValue = diff.sqrMagnitude;
            if (diffValue <= speedValue * speedValue)
            {
                unit.Play("Idle");
                unit.Data.SetForward(unit.Data.birthForward);
                unit.Data.isInBirthPosition = true;
                return diff;
                
            }
            else
            {
                unit.Play("Run");
                unit.Data.isInBirthPosition = false;
                return diff.normalized * speedValue;
            }
        }
    }
}